import { Button, ScrollView, Text, useToast, View } from 'native-base';
import React, { useEffect } from 'react';
import { Modal, SafeAreaView, StyleSheet, TouchableOpacity } from 'react-native';
import { CommonStyle } from '../../../common/commonStyle.ts';
import Entypo from 'react-native-vector-icons/Entypo';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import Tools, { IShoppingCartDiscountResult } from '../../../utils/Tools.ts';
import { useReactive } from 'ahooks';
import { removeShoppingCart, updateShoppingCart, updateShoppingCartSku } from '../../../redux/reducers/app.ts';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import Feather from 'react-native-vector-icons/Feather';
import { FasterImageView } from '@candlefinance/faster-image';
import AntDesign from 'react-native-vector-icons/AntDesign';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { ShowConfirmDialog } from '../../../component/ConfirmDialog.tsx';
import EmptyCom from '../../../component/Empty.tsx';

interface IShoppingCartProps {
  visible?: boolean;
}
interface IState {
  price: number;
  favorablePrice: number;
  visible: boolean;
  shoppingCartDiscount: IShoppingCartDiscountResult[];
}
const ShoppingCart: React.FC<IShoppingCartProps> = (props) => {
  const shoppingCart = useSelector((state: RootState) => state.shoppingCart);
  const dispatch = useDispatch<AppDispatch>();
  const state = useReactive<IState>({ price: 0, favorablePrice: 0, visible: false, shoppingCartDiscount: [] });
  const toast = useToast();

  useEffect(() => {
    const invalidProduct: string[] = [];
    shoppingCart.forEach((item) => {
      const hasSell = Tools.hasProductInSaleTime(item);
      if (!hasSell) {
        invalidProduct.push(item.name);
        dispatch(removeShoppingCart(item.goodsId));
      }
    });
    if (invalidProduct.length > 0) toast.show({ description: invalidProduct.toString().replace(/,/g, '-') + '不在可售时间，已从购物车中删除' });
  }, []);

  useEffect(() => {
    state.shoppingCartDiscount = Tools.calculateShoppingCartDiscount(shoppingCart).results;
    state.price = Tools.calculateShoppingCartDiscount(shoppingCart).totalPrice;
    state.favorablePrice = Tools.calculateShoppingCartDiscount(shoppingCart).totalDiscountPrice;
  }, [shoppingCart]);

  useEffect(() => {
    state.visible = props.visible || false;
  }, [props.visible]);

  // 单品产品购物车加减
  const handleOperationProductToShoppingCart = (type: 'add' | 'remove', data: IProductInformation) => {
    if (data.sku) {
      dispatch(updateShoppingCartSku({ type, data: { ...data, nums: 1 } }));
    } else {
      dispatch(updateShoppingCart({ type, data }));
    }
  };

  // 渲染购物车底部工具导航栏
  const renderNavigationBar = () => {
    return (
      <View style={styles.container}>
        <Touchable style={{ flexDirection: 'row', alignItems: 'center', height: 45 }} onPress={() => (state.visible = true)}>
          <View style={{ width: 45, height: 45, borderRadius: 20, position: 'relative' }} justifyContent={'center'} alignItems={'center'} bg={CommonStyle.mainColor}>
            <Entypo name={'shopping-bag'} size={28} color={'white'} />
            {Tools.getShoppingCartProductQuantity(shoppingCart) > 0 && (
              <View style={styles.badge}>
                <Text fontSize={10} color={'white'}>
                  {Tools.getShoppingCartProductQuantity(shoppingCart)}
                </Text>
              </View>
            )}
          </View>
          <View justifyContent={'flex-start'} mt={-1} ml={6}>
            <View flexDirection={'row'} alignItems={'flex-end'}>
              <Text fontSize={12} marginBottom={1} color={'#ff5a00'}>
                ¥
              </Text>
              <Text fontSize={20} fontWeight={'bold'} ml={1} color={'#ff5a00'}>
                {state.price || '0'}
              </Text>
            </View>
            {state.favorablePrice > 0 && (
              <Text fontSize={10} color={CommonStyle.deepGrey}>
                优惠¥ {state.favorablePrice}
              </Text>
            )}
          </View>
        </Touchable>

        <View style={{ width: 100, height: 45, position: 'relative', zIndex: 999 }}>
          <Button bg={CommonStyle.mainColor} width={'100%'} height={'100%'} py={0} borderRadius={25} _pressed={{ bg: CommonStyle.btnSelectMainColor }} onPress={() => {}}>
            {Tools.getShoppingCartProductQuantity(shoppingCart) > 0 ? '去结算' : '去选购'}
          </Button>
        </View>
      </View>
    );
  };

  // 清空购物车
  const handleEmptyShoppingCart = () => {
    ShowConfirmDialog({ title: '提示', message: '确定清空购物车吗？' }).then(() => {
      dispatch(removeShoppingCart());
    });
  };

  // 渲染原价
  const renderOriginalPrice = (item: IProductInformation) => {
    const productDiscount = state.shoppingCartDiscount.find((_item) => (item.goodsType === 2 ? _item.sku === item.sku : _item.variantId === item.variantId));
    if (!productDiscount) return null;
    if (productDiscount.activeCount > 0 && productDiscount.salePriceCount > 0) {
      return (
        <View flexDirection={'row'} alignItems={'center'}>
          <Text fontWeight={'bold'} color={CommonStyle.price}>
            ¥{productDiscount.salePrice}
          </Text>
          <Text fontSize={10} ml={2} color={CommonStyle.deepGrey}>
            原价
          </Text>
          <Text fontSize={10} ml={1} color={CommonStyle.deepGrey}>
            x{productDiscount.salePriceCount}
          </Text>
        </View>
      );
    }
    return null;
  };

  // 渲染价格与折扣
  const renderPriceAndDiscount = (item: IProductInformation) => {
    const productDiscount = state.shoppingCartDiscount.find((_item) => (item.goodsType === 2 ? _item.sku === item.sku : _item.variantId === item.variantId));
    if (!productDiscount) return null;
    return (
      <View flexDirection={'row'} alignItems={'center'} flex={1} overflow={'hidden'}>
        <Text fontWeight={'bold'} color={CommonStyle.price}>
          ¥{productDiscount.activeCount ? productDiscount.activePrice : productDiscount.salePrice}
        </Text>
        {productDiscount.activeCount > 0 && (
          <>
            <Text fontSize={10} ml={2} color={CommonStyle.price}>
              {((productDiscount.activePrice / item.price) * 10).toFixed(0)}折，限{productDiscount.maxNum}份
            </Text>
            <Text fontSize={10} ml={1} color={CommonStyle.price}>
              x{productDiscount.activeCount}
            </Text>
          </>
        )}
      </View>
    );
  };

  // 渲染产品列表
  const renderProductListItem = (item: IProductInformation, index: number) => {
    const styles = StyleSheet.create({
      list: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 22 },
      imgBox: { width: 80, height: 80, borderRadius: 8, overflow: 'hidden', position: 'relative' },
      mask: { position: 'absolute', width: 80, height: 80, top: 0, backgroundColor: 'rgba(0,0,0,0.1)', zIndex: 9, alignItems: 'center', justifyContent: 'center' },
      right: { flex: 1, paddingLeft: 12, minHeight: 80, justifyContent: 'space-between' },
      top: { flexDirection: 'row', justifyContent: 'space-between', width: '100%' },
      price: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: '100%' },
    });
    return (
      <View key={index} style={[styles.list, { opacity: Tools.renderProductValidation(item) <= 2 ? 0.4 : 1 }]}>
        <View style={styles.imgBox}>
          <FasterImageView style={{ flex: 1 }} source={{ url: item.mainImage, transitionDuration: 0.3, resizeMode: 'cover', cachePolicy: 'discWithCacheControl', showActivityIndicator: true }} />
          {item.oneIsVideo === 2 && (
            <View style={styles.mask}>
              <AntDesign name={'play'} size={33} />
            </View>
          )}
        </View>
        <View style={styles.right}>
          <View style={styles.top}>
            <Text flex={1} numberOfLines={1} fontWeight={'bold'} fontSize={12}>
              {item.name}
            </Text>
          </View>
          <View width={'100%'} paddingY={1}>
            {item.goodsType === 1 && (
              <Text fontSize={11} numberOfLines={1} backgroundColor={'#ec820d'} color={CommonStyle.lightGray}>
                {item.sku ? item.sku.replace(/:/g, '、') : ''}
              </Text>
            )}
            {item.goodsType === 2 && (
              <Text fontSize={11} numberOfLines={2} backgroundColor={'#ec820d'} color={CommonStyle.lightGray}>
                {item.sku ? item.sku.replace(/___|(\|\|\|)/g, '、') : ''}
              </Text>
            )}
          </View>
          {renderOriginalPrice(item)}
          <View style={styles.price}>
            {renderPriceAndDiscount(item)}
            <View flexDirection={'row'}>
              {shoppingCart.find((_item) => _item.goodsId === item.goodsId) && (
                <>
                  <TouchableOpacity onPress={() => handleOperationProductToShoppingCart('remove', item)}>
                    <Ionicons name={'remove-circle'} size={26} color={CommonStyle.mainColor} />
                  </TouchableOpacity>
                  {!item.sku && <Text mx={2}>{shoppingCart.find((_item) => _item.goodsId === item.goodsId)?.nums}</Text>}
                  {item.sku && <Text mx={2}>{shoppingCart.find((_item) => _item.goodsId === item.goodsId && _item.sku === item.sku)?.nums}</Text>}
                </>
              )}
              <TouchableOpacity onPress={() => handleOperationProductToShoppingCart('add', item)}>
                <Ionicons name={'add-circle'} size={26} color={CommonStyle.mainColor} />
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </View>
    );
  };

  return (
    <React.Fragment>
      <SafeAreaView>{renderNavigationBar()}</SafeAreaView>

      <Modal visible={state.visible} transparent animationType="fade">
        <View style={styles.containerModal}>
          <Touchable style={styles.touchArea} onPress={() => (state.visible = false)}>
            <View></View>
          </Touchable>
          <View style={styles.pickerContainer}>
            <View style={styles.pickerContent}>
              <View backgroundColor={'red'} px={4} py={2} flexDirection={'row'} width={'100%'} alignItems={'center'} justifyContent={'space-between'} borderBottomWidth={0.5} borderColor={CommonStyle.borderColor}>
                <Text marginRight={20}>购物车</Text>
                <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={handleEmptyShoppingCart}>
                  <Feather name={'trash-2'} />
                  <Text fontSize={12} ml={1}>
                    清除购物车
                  </Text>
                </TouchableOpacity>
              </View>
              <ScrollView flex={1} contentContainerStyle={{ padding: 16 }}>
                {shoppingCart.map((item, index) => {
                  return renderProductListItem(item, index);
                })}
                {shoppingCart.length === 0 && <EmptyCom text={'暂无数据'} height={290} />}
              </ScrollView>
              {renderNavigationBar()}
            </View>
          </View>
        </View>
      </Modal>
    </React.Fragment>
  );
};
const styles = StyleSheet.create({
  container: { paddingHorizontal: 16, paddingBottom: 20, backgroundColor: 'white', paddingTop: 12, flexDirection: 'row', justifyContent: 'space-between', borderTopWidth: 0.5, borderColor: CommonStyle.borderColor },
  badge: { position: 'absolute', width: 20, height: 20, backgroundColor: 'red', right: -10, top: 0, zIndex: 9, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
  containerModal: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0.2)' },
  touchArea: { flex: 1, backgroundColor: 'rgba(0,0,0,0.2)' },
  pickerContainer: { backgroundColor: 'rgba(0,0,0,0.2)' },
  pickerContent: { position: 'relative', height: 450, borderTopLeftRadius: 20, borderTopRightRadius: 20, backgroundColor: '#fff' },
});
export default ShoppingCart;
